<template>
  <div>
    <h1>Sub App 1 - Home Page</h1>
    <img src="@/assets/big.png" alt="" />
    <h1>数据：</h1>
    <div>{{ showData }}</div>
    <br />
    <div>
      <button @click="handleClick">跳转到about</button>
      <template v-if="isMicroApp">
        <button @click="handleGoMain('/about')">跳转到主应用 about 页</button>
        <button @click="handleClickSubApp1">跳转到sub-app-2</button>
        <button @click="handleSendData">向主应用发送数据</button>
      </template>
    </div>
    <h1>{{ route.path }}</h1>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import { customLog } from "@/utils/log";
import { ref, computed } from "vue";
const route = useRoute();
const router = useRouter();

const isMicroApp = window?.__MICRO_APP_ENVIRONMENT__;

const data = ref({});

const showData = computed(() => {
  return JSON.stringify(data?.value);
});

if (isMicroApp) {
  // 返回主应用下发的data数据
  data.value = window.microApp.getData();

  // 监听主应用数据
  window.microApp.addDataListener((newData) => {
    customLog("来自主应用的数据：", newData);
    data.value = newData;

    return "ok";
  });
}

const handleClick = () => {
  router.push("/about");
};
const handleSendData = () => {
  window.microApp.dispatch(
    {
      age: 100,
    },
    (res) => {
      customLog("数据发送成功！");
      if (res) {
        customLog("收到主应用的回复：", res);
      }
    }
  );
};
const handleGoMain = (path) => {
  router.push(path);
};
</script>

<style scoped>
img {
  width: 500px;
  height: 350px;
}
</style>
